<template>
  <a-modal
    :open="visible"
    :keyboard="false"
    :maskClosable="false"
    title="选择API接口"
    @cancel="onCancel"
    @ok="onSuccess"
    :width="750"
  >
    <div class="section">
      <div class="row row-header">
        <div class="cell code">接口编码</div>
        <div class="cell name">接口名称</div>
        <div class="cell url">接口地址</div>
      </div>
      <a-radio-group v-model:value="selectedCode" style="display: block">
        <div
          :key="item.code"
          v-for="(item, index) in apiConfigItems"
          class="row"
          :class="{
            selected: item.code == selectedCode,
          }"
        >
          <a-radio :value="item.code">
            <div class="row row-noborder">
              <div class="cell code">{{ item.code }}</div>
              <div class="cell name">{{ item.name }}</div>
              <div class="cell url">/api/report/query/{{ item.code }}</div>
            </div>
          </a-radio>
        </div>
      </a-radio-group>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { HttpApiConfigDto } from "@/api/report/types";
import api from "@/api/report/httpApiConfig";
import { onMounted, ref } from "vue";
import { message } from "ant-design-vue";

const props = defineProps({
  visible: { type: Boolean, required: true },
  value: { type: String, required: true },
});
const emits = defineEmits([
  "success",
  "update:value",
  "update:url",
  "update:visible",
]);

const selectedCode = ref<string>();

const onSuccess = () => {
  if (selectedCode.value) {
    emits("update:value", selectedCode.value);
    emits("update:url", " /api/report/query/" + selectedCode.value);
    emits("update:visible", false);
    emits("success");
  } else {
    message.error("请选择API接口");
  }
};

const onCancel = () => {
  emits("update:visible", false);
};

const apiConfigItems = ref<Array<HttpApiConfigDto>>([]);

const loadApiConfigs = () => {
  api.getAllList({ Status: true }).then((res) => {
    apiConfigItems.value = res.items;
  });
};

onMounted(() => {
  loadApiConfigs();
});
</script>

<style lang="less" scoped>
:deep(.ant-radio-wrapper) {
  display: flex;
  flex: 1;
  > span:last-child {
    flex: 1;
  }
}

.row {
  border-bottom: 1px solid #ddd;
  padding: 5px 10px;
  display: flex;

  &.selected {
    background: rgba(0, 128, 240, 0.25);
  }
  &:hover {
    background: rgba(0, 128, 240, 0.1);
  }

  &-noborder {
    border-bottom: none;
    padding: 0;
    &:hover {
      background-color: transparent;
    }
  }

  .cell {
    &.name {
      flex: 1;
    }
    &.code {
      flex: 1;
    }
    &.url {
      flex: 1;
    }
  }

  &-header {
    padding-left: 35px;
    background-color: #f9f9f9;
  }
}

.section {
  border: 1px solid #ddd;
}
</style>
